package com.art.sunflower.config;

import com.art.sunflower.util.Md5SaltTool;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 验证器，增加了登录次数校验功能
 *
 * @author 徐鑫
 */
public class RetryLimitCredentialsMatcher extends SimpleCredentialsMatcher {
    private static final Logger log = LoggerFactory.getLogger(RetryLimitCredentialsMatcher.class);

    //集群中可能会导致出现验证多过5次的现象，因为AtomicInteger只能保证单节点并发
    private Cache<String, AtomicInteger> loginRetryCache;

    private int maxRetryCount = 5;//登录次数限制

    /**
     * 设置尝试登录次数限制
     */
    void setMaxRetryCount() {
        this.maxRetryCount = 5;
    }

    /**
     * 获取登录次数限制
     *
     * @return 登录次数限制
     */
    public int getMaxRetryCount() {
        return maxRetryCount;
    }

    /**
     * 有参构造器
     *
     * @param cacheManager        缓存器
     * @param loginRetryCacheName 缓存器名
     */
    public RetryLimitCredentialsMatcher(CacheManager cacheManager, String loginRetryCacheName) {
        loginRetryCache = cacheManager.getCache(loginRetryCacheName);
    }

    /**
     * 根据用户提交的令牌和已存信息进行比对
     *
     * @param token 用户提交的令牌
     * @param info  已存信息
     * @return 登录状态
     */
    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        String username = (String) token.getPrincipal();
        String password = String.valueOf((char[]) token.getCredentials());
        //增加尝试次数
        AtomicInteger retryCount = loginRetryCache.get(username);
        //若是此账号未被归入池中
        if (null == retryCount) {
            retryCount = new AtomicInteger(0);//计数器归0
            loginRetryCache.put(username, retryCount);//在池中第一次归入
        }
        if (retryCount.incrementAndGet() > maxRetryCount) {
            log.warn("username: " + username + " tried to login more than 5 times in period");
            throw new ExcessiveAttemptsException("username: " + username + " tried to login more than 5 times in period"
            );
        }

        //进行密码比对
        boolean matches = Md5SaltTool.validPassword(password, (String) info.getCredentials());
        //登录成功
        if (matches)
            //清除密码登录次数计数
            loginRetryCache.remove(username);
        return matches;
    }
}
